package org.ala.tiktools.tools;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

/**
 * Environment 帮助类
 *
 * @author ala
 * @date 2025-04-04 11:06
 */
public class EnvironmentTools {


    /**
     *  解析配置项
     *  <p> 解析给定字符串中的${}部分，若解析出的${}部分在env中找不到直接抛异常
     */
    public static String parseValue(String str, Environment env) {
        //  遍历，遇到${标识配置项开头，遇到}标识配置项结尾
        List<String> vals = new ArrayList<>();
        List<Boolean> tags = new ArrayList<>();

        char[] cs = str.toCharArray();
        int l = 0;
        for (int i = 0 ; i < cs.length ; i++) {
            if (cs[i] == '$') {
                if (i != l) {
                    vals.add(new String(cs, l, i - l));
                    tags.add(false);
                }
                l = i+2;
                i++;
            } else if (cs[i] == '}') {
                vals.add(new String(cs, l, i - l));
                tags.add(true);
                l = i+1;
            }
        }
        if (l < cs.length) {
            vals.add(new String(cs, l, cs.length - l));
            tags.add(false);
        }

        StringBuilder sbuf = new StringBuilder();
        for (int i = 0 ; i < vals.size() ; i++) {
            if (!tags.get(i)) {
                sbuf.append(vals.get(i));
            } else {
                sbuf.append(env.getProperty(vals.get(i)));
            }
        }
        return sbuf.toString();
    }
    
    
    /**
     * 	按照前缀读取一级配置项
     */
    public static Set<String> items(String prefix, ConfigurableEnvironment env) {
    	MutablePropertySources mpss = env.getPropertySources();
    	Set<String> res = new HashSet<>();
    	for (PropertySource<?> ps : mpss) {
    		if (ps instanceof MapPropertySource) {
    			MapPropertySource mps = (MapPropertySource) ps;
    			for (String n : mps.getPropertyNames()) {
    				//	以prefix为前缀，并且后面不含'.'
    				if (n.startsWith(prefix)) {
    					n = n.replace(prefix, "");
    					String[] ss = n.split("\\.");
    					res.add(ss[0]);
    				}
    			}
    		}
    	}
    	return res;
    }
    
}
